package com.example.bookshop.controller;

import com.example.bookshop.VO.CartItemVO;
import com.example.bookshop.entity.*;
import com.example.bookshop.service.OrderService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.math.BigDecimal;
import java.security.Principal;
import java.util.List;

/**
 * @auth shanyue
 * @date 2025年06月04日18:48
 */
@Controller
@RequestMapping("/order")
public class OrderController {
    @Resource
    private OrderService orderService;

    @PostMapping("/checkout")
    public String checkoutPage(Principal principal, Model model) {
        String username = principal.getName();
        List<CartItemVO> cartItems = orderService.getCartItemsForCheckout(username);

        if (cartItems.isEmpty()) {
            model.addAttribute("msg", "购物车无有效商品，无法结算");
            return "cart";
        }

        BigDecimal totalPrice = cartItems.stream()
                .map(CartItemVO::getSubTotal)
                .reduce(BigDecimal.ZERO, BigDecimal::add);

        model.addAttribute("cartItems", cartItems);
        model.addAttribute("totalPrice", totalPrice);

        return "checkout";
    }

    @PostMapping("/submit")
    public String submitOrder(Principal principal, Model model) {
        String username = principal.getName();
        String msg = orderService.submitOrder(username);

        model.addAttribute("msg", msg);

        List<Book> books = orderService.getBooks();
        model.addAttribute("books", books);

        return "index";
    }
}
